package top.myliangsl.newsapplets.service.jdApi;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
import top.myliangsl.newsapplets.configuration.properties.JdApiProperties;
import top.myliangsl.newsapplets.constant.JdNewsCodeConstant;
import top.myliangsl.newsapplets.domain.po.TNewsChannel;
import top.myliangsl.newsapplets.domain.po.jdApi.JdNewsChannelDto;
import top.myliangsl.newsapplets.domain.po.jdApi.JdNewsDto;
import top.myliangsl.newsapplets.service.TNewsChannelService;
import top.myliangsl.newsapplets.service.TNewsService;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 京东万象API请求实体
 *
 * @author xiaoliang
 */
@Service
@Slf4j
public class JdApiService {
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private JdApiProperties jdApiProperties;
    @Resource
    private TNewsChannelService tNewsChannelService;
    @Resource
    private TNewsService tNewsService;

    /**
     * 操作获取新闻渠道列表
     */
    public void operateNewsChannel() {
        String s = requestNewsChannelApi();
        if (StringUtils.isBlank(s)) {
            return;
        }
        JdNewsChannelDto dto = JSON.parseObject(s, JdNewsChannelDto.class);
        if (dto.getCode().equalsIgnoreCase(JdNewsCodeConstant.SUCCESS)) {
            Integer status = dto.getResult().getStatus();
            if (status != 0) {
                log.error("请求京东万象API出现位置错误，{}", s);
                return;
            }
            List<String> result = dto.getResult().getResult();
            if (!CollectionUtils.isEmpty(result)) {
                result.forEach(rs -> {
                    tNewsChannelService.insertNewsChannel(rs);
                });
            }
        } else {
            log.error("请求京东万象API出现位置错误，{}", s);
        }
    }

    private String requestNewsChannelApi() {
        String url = String.format(jdApiProperties.getNewsChannelApiUrl(), jdApiProperties.getAppKey());
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        return responseEntity.getStatusCode() == HttpStatus.OK ? responseEntity.getBody() : null;
    }

    /**
     * 拉去新闻列表并入库
     */
    public void operateNews() {
        List<TNewsChannel> list = tNewsChannelService.list();
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        list.stream().parallel().forEach(dt -> {
            String s = requestNewsListApi(dt.getChannelName(), 40, 0);
            log.info(s);
            if (StringUtils.isBlank(s)) {
                log.error("拉去新闻出现未知异常,{}", s);
                return;
            }
            JdNewsDto newsDto = JSON.parseObject(s, JdNewsDto.class);
            if (Objects.isNull(newsDto)) {
                log.error("拉去新闻出现未知异常,{}", s);
                return;
            }
            if (newsDto.getCode().equals(JdNewsCodeConstant.SUCCESS) && newsDto.getResult().getStatus() == 0) {
                JdNewsDto.ResultDTO.ResultChannelDTO result = newsDto.getResult().getResult();
                if (Objects.nonNull(result)) {
                    tNewsService.insertNewsChannel(result.getChannel(), result.getList());
                }
            }
        });
    }

    public String requestNewsListApi(String channelName, Integer num, Integer start) {
        String url = String.format(jdApiProperties.getNewsApiUrl(), channelName, num, start, jdApiProperties.getAppKey());
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        return responseEntity.getStatusCode() == HttpStatus.OK ? responseEntity.getBody() : null;
    }
}
